import React, { useEffect, useState } from 'react';
import {
  Card,
  Tree,
  Button,
  Modal,
  Form,
  Input,
  Select,
  Space,
  message,
  Popconfirm,
  Typography,
  Row,
  Col,
  Tag,
  Tooltip,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  DragOutlined,
  FolderOutlined,
  FolderOpenOutlined,
} from '@ant-design/icons';
import type { DataNode, TreeProps } from 'antd/es/tree';
import { useAppDispatch } from '../../store';
import { setBreadcrumbs } from '../../store/slices/uiSlice';

const { Title, Text } = Typography;
const { Option } = Select;

interface Category {
  id: string;
  name: string;
  description?: string;
  parentId?: string;
  level: number;
  sort: number;
  status: 'active' | 'inactive';
  productCount: number;
  children?: Category[];
}

interface CategoryFormData {
  name: string;
  description?: string;
  parentId?: string;
  status: 'active' | 'inactive';
  sort: number;
}

const CategoryManagement: React.FC = () => {
  const dispatch = useAppDispatch();
  const [form] = Form.useForm();
  
  const [categories, setCategories] = useState<Category[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingCategory, setEditingCategory] = useState<Category | null>(null);
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);

  useEffect(() => {
    dispatch(setBreadcrumbs([
      { title: '商品管理' },
      { title: '分类管理' },
    ]));
  }, [dispatch]);

  // 加载分类数据
  useEffect(() => {
    loadCategories();
  }, []);

  const loadCategories = async () => {
    try {
      setLoading(true);
      // 模拟分类数据
      const mockCategories: Category[] = [
        {
          id: '1',
          name: '电子产品',
          description: '各类电子设备和数码产品',
          level: 1,
          sort: 1,
          status: 'active',
          productCount: 150,
          children: [
            {
              id: '11',
              name: '手机通讯',
              description: '智能手机、功能机等',
              parentId: '1',
              level: 2,
              sort: 1,
              status: 'active',
              productCount: 80,
              children: [
                {
                  id: '111',
                  name: '智能手机',
                  parentId: '11',
                  level: 3,
                  sort: 1,
                  status: 'active',
                  productCount: 60,
                },
                {
                  id: '112',
                  name: '功能手机',
                  parentId: '11',
                  level: 3,
                  sort: 2,
                  status: 'active',
                  productCount: 20,
                },
              ],
            },
            {
              id: '12',
              name: '电脑办公',
              description: '笔记本、台式机、办公设备',
              parentId: '1',
              level: 2,
              sort: 2,
              status: 'active',
              productCount: 70,
              children: [
                {
                  id: '121',
                  name: '笔记本电脑',
                  parentId: '12',
                  level: 3,
                  sort: 1,
                  status: 'active',
                  productCount: 40,
                },
                {
                  id: '122',
                  name: '台式机',
                  parentId: '12',
                  level: 3,
                  sort: 2,
                  status: 'active',
                  productCount: 30,
                },
              ],
            },
          ],
        },
        {
          id: '2',
          name: '服装鞋帽',
          description: '男装、女装、童装、鞋类等',
          level: 1,
          sort: 2,
          status: 'active',
          productCount: 200,
          children: [
            {
              id: '21',
              name: '男装',
              parentId: '2',
              level: 2,
              sort: 1,
              status: 'active',
              productCount: 80,
            },
            {
              id: '22',
              name: '女装',
              parentId: '2',
              level: 2,
              sort: 2,
              status: 'active',
              productCount: 120,
            },
          ],
        },
        {
          id: '3',
          name: '家居生活',
          description: '家具、家纺、厨具等',
          level: 1,
          sort: 3,
          status: 'active',
          productCount: 100,
        },
      ];
      
      setCategories(mockCategories);
      setExpandedKeys(['1', '2', '3']);
    } catch (error) {
      message.error('加载分类数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 转换为Tree组件需要的数据格式
  const convertToTreeData = (categories: Category[]): DataNode[] => {
    return categories.map(category => ({
      key: category.id,
      title: (
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ marginRight: 8 }}>{category.name}</span>
            <Tag color={category.status === 'active' ? 'green' : 'red'} size="small">
              {category.status === 'active' ? '启用' : '禁用'}
            </Tag>
            <Tag color="blue" size="small">
              {category.productCount} 商品
            </Tag>
          </div>
          <Space size="small">
            <Tooltip title="添加子分类">
              <Button
                type="text"
                size="small"
                icon={<PlusOutlined />}
                onClick={(e) => {
                  e.stopPropagation();
                  handleAdd(category.id);
                }}
              />
            </Tooltip>
            <Tooltip title="编辑">
              <Button
                type="text"
                size="small"
                icon={<EditOutlined />}
                onClick={(e) => {
                  e.stopPropagation();
                  handleEdit(category);
                }}
              />
            </Tooltip>
            <Tooltip title="删除">
              <Popconfirm
                title="确定要删除这个分类吗？"
                onConfirm={(e) => {
                  e?.stopPropagation();
                  handleDelete(category.id);
                }}
                onCancel={(e) => e?.stopPropagation()}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  type="text"
                  size="small"
                  icon={<DeleteOutlined />}
                  danger
                  onClick={(e) => e.stopPropagation()}
                />
              </Popconfirm>
            </Tooltip>
          </Space>
        </div>
      ),
      icon: category.children && category.children.length > 0 ? 
        <FolderOpenOutlined /> : <FolderOutlined />,
      children: category.children ? convertToTreeData(category.children) : undefined,
    }));
  };

  // 添加分类
  const handleAdd = (parentId?: string) => {
    setEditingCategory(null);
    form.resetFields();
    form.setFieldsValue({
      parentId,
      status: 'active',
      sort: 1,
    });
    setModalVisible(true);
  };

  // 编辑分类
  const handleEdit = (category: Category) => {
    setEditingCategory(category);
    form.setFieldsValue({
      name: category.name,
      description: category.description,
      parentId: category.parentId,
      status: category.status,
      sort: category.sort,
    });
    setModalVisible(true);
  };

  // 删除分类
  const handleDelete = async (id: string) => {
    try {
      // await CategoryService.deleteCategory(id);
      message.success('删除成功');
      loadCategories();
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 保存分类
  const handleSave = async (values: CategoryFormData) => {
    try {
      if (editingCategory) {
        // await CategoryService.updateCategory(editingCategory.id, values);
        message.success('更新成功');
      } else {
        // await CategoryService.createCategory(values);
        message.success('创建成功');
      }
      
      setModalVisible(false);
      loadCategories();
    } catch (error) {
      message.error(editingCategory ? '更新失败' : '创建失败');
    }
  };

  // 获取父分类选项
  const getParentOptions = (categories: Category[], excludeId?: string): any[] => {
    const options: any[] = [];
    
    const traverse = (cats: Category[], level = 0) => {
      cats.forEach(cat => {
        if (cat.id !== excludeId) {
          options.push({
            value: cat.id,
            label: '　'.repeat(level) + cat.name,
            disabled: level >= 2, // 最多支持3级分类
          });
          if (cat.children) {
            traverse(cat.children, level + 1);
          }
        }
      });
    };
    
    traverse(categories);
    return options;
  };

  const treeData = convertToTreeData(categories);

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Title level={3} style={{ margin: 0 }}>
            商品分类管理
          </Title>
          <Button type="primary" icon={<PlusOutlined />} onClick={() => handleAdd()}>
            添加根分类
          </Button>
        </div>

        <Tree
          showIcon
          draggable
          blockNode
          expandedKeys={expandedKeys}
          selectedKeys={selectedKeys}
          treeData={treeData}
          onExpand={setExpandedKeys}
          onSelect={setSelectedKeys}
          style={{ background: '#fafafa', padding: '16px', borderRadius: '8px' }}
        />
      </Card>

      {/* 添加/编辑分类模态框 */}
      <Modal
        title={editingCategory ? '编辑分类' : '添加分类'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSave}
        >
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="分类名称"
                name="name"
                rules={[{ required: true, message: '请输入分类名称' }]}
              >
                <Input placeholder="请输入分类名称" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="父分类" name="parentId">
                <Select placeholder="选择父分类（不选则为根分类）" allowClear>
                  {getParentOptions(categories, editingCategory?.id).map(option => (
                    <Option key={option.value} value={option.value} disabled={option.disabled}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item label="分类描述" name="description">
            <Input.TextArea rows={3} placeholder="请输入分类描述" />
          </Form.Item>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item label="状态" name="status">
                <Select>
                  <Option value="active">启用</Option>
                  <Option value="inactive">禁用</Option>
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item label="排序" name="sort">
                <Input type="number" placeholder="数字越小排序越靠前" />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default CategoryManagement;
